/**********************************************
** @Des: This file ...
** @Author: xiaomeng79
** @Date:   17-11-20 下午6:07
***********************************************/
package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"errors"
	"time"
)

type Role struct {
	Id int
	Role_name string
	Created_at int64
	Updated_at int64
	Is_usable int
}

/**
设置表名称
 */
func (a *Role) TableName() string {
	return "rbac_role"
}

/**
增加
 */
func (a *Role) Add(pri_ids []int) (error) {
	if err := a.valid("add");err != nil {
		return err
	}
	 o := orm.NewOrm()
	 //执行事物
	 o.Begin()
	//新增角色
	 id,err := o.Insert(a)
	if err != nil {
		o.Rollback()
		return errors.New("新增角色失败")
	}
	//新增角色权限
	p,_ := o.Raw("INSERT INTO rbac_role_pri (role_id,pri_id) VALUES (?,?)").Prepare()
	for _,pri_id := range pri_ids {
		_,err = p.Exec(id,pri_id)
		if err != nil {
			o.Rollback()
			return errors.New("新增角色失败")
		}
	}
	p.Close()
	o.Commit()
	return nil
}

/**
列表
 */
func (a *Role) Lst() (interface{}) {

	o := orm.NewOrm()
	var maps []orm.Params
	sql := `SELECT r.id,r.role_name,r.created_at,GROUP_CONCAT(p.pri_name) as pri_names from rbac_role as r
			LEFT JOIN rbac_role_pri as rp ON rp.role_id = r.id
			LEFT JOIN rbac_privilege as p ON p.id = rp.pri_id and p.is_usable = 1
			WHERE r.is_usable = 1
			GROUP BY(r.id)
	`
	o.Raw(sql).Values(&maps)
	return maps

}

/**
获取角色列表
 */
func (a *Role) GetRoleLst() interface{} {
	o := orm.NewOrm()
	maps := make([]orm.Params,0)

	o.Raw("SELECT id,role_name FROM rbac_role WHERE is_usable = 1").Values(&maps)
	return maps
}

/**
获取对象用ID
 */
func GetRoleById(id int) (map[string]interface{}, error) {
	o := orm.NewOrm()
	res := make([]orm.Params,1)
	sql := `SELECT r.id,r.role_name,r.created_at,GROUP_CONCAT(rp.pri_id) AS pri_ids FROM rbac_role AS r
			LEFT JOIN rbac_role_pri AS rp ON rp.role_id = r.id
			WHERE r.is_usable = 1 AND r.id = ?
			GROUP BY r.id
			LIMIT 1`
	num, err := o.Raw(sql,id).Values(&res)
	if err != nil || num != 1 {
		return nil, errors.New("获取对象失败")
	}
	return res[0], nil
}

/**
修改
 */
func (a *Role) Edit(pri_ids []int, fields ...string) (error) {

	o := orm.NewOrm()
	//执行事物
	o.Begin()
	//新增角色
	_,err := o.Update(a, fields...)
	if err != nil {
		o.Rollback()
		return errors.New("修改角色失败")
	}
	//删除旧的角色权限
	p1,_ := o.Raw("DELETE FROM rbac_role_pri WHERE role_id = ?").Prepare()
	_,err = p1.Exec(a.Id)
	if err != nil {
		o.Rollback()
		return errors.New("修改角色失败")
	}
	//新增角色权限
	p,_ := o.Raw("INSERT INTO rbac_role_pri (role_id,pri_id) VALUES (?,?)").Prepare()
	for _,pri_id := range pri_ids {
		_,err = p.Exec(a.Id,pri_id)
		if err != nil {
			o.Rollback()
			return errors.New("修改角色失败")
		}
	}
	p1.Close()
	p.Close()
	o.Commit()
	return nil
}

/**
删除
 */
func (a *Role) Del(id int) error {
	o := orm.NewOrm()

	p,_ := o.Raw("UPDATE rbac_role SET is_usable = 0 , updated_at = ? where id = ?").Prepare()
	_,err := p.Exec(time.Now().Unix(),id)
	p.Close()
	if err != nil {
		return errors.New("删除角色失败")
	}
	return nil
}


/**
数据验证
 */
func (a *Role) valid(str string) (error) {
	v := validation.Validation{}

	//公共的
	if res := v.Required(a.Role_name, "角色名称"); !res.Ok {
		return errors.New(res.Error.Key+res.Error.Message)
	}
	//add需要验证的
	if str == "add" {
		cnt,_ := orm.NewOrm().QueryTable(a.TableName()).Filter("role_name",a.Role_name).Filter("is_usable",1).Count()
		if cnt > 0 {
			return errors.New(a.Role_name+"角色已经存在")
		}
	}

	return nil

}

